#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/29 16:31
# @Author  : LiShan
# @Email   : lishan_1997@126.com
# @File    : contour_match.py
# @Note    : this is note
import cv2.cv2 as cv
import numpy as np


def template(template):
    temp = cv.imread(template, 0)
    # temp_gray = cv.cvtColor(temp, cv.COLOR_BGR2GRAY)
    _, temp_thresh = cv.threshold(temp, 127, 255, 0)
    plate_contours, temp_hierarchy = cv.findContours(temp_thresh, 2, 1)
    return plate_contours, temp_hierarchy


def matchTemp(img):
    # 模版特征
    templates_contours = []
    fang_contours, temp_hierarchy = template('./templte/left.png')
    hua_contours, temp_hierarchy = template('./templte/straight.png')
    circle_contours, temp_hierarchy = template('./pic/turn.png')
    templates_contours = [fang_contours[0], hua_contours[0], circle_contours[0]]
    # print(fang_contours[0])
    # templates_contours = sorted(templates_contours, key=lambda x: x[0])

    # cv.drawContours(temp, hua_contours, 0, (0, 0, 255), 2)  # 花盘子
    # cv.drawContours(temp, fang_contours, 1, (0, 255, 0), 2)  # 方盘子

    # 盘子特征
    img = cv.imread(img)
    img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    _, img_thresh = cv.threshold(img_gray, 150, 255, 0)
    # 腐蚀 >> 膨胀
    kernel_1 = np.ones((5, 5), np.uint8)
    kernel_2 = np.ones((5, 5), np.uint8)
    img_erosion = cv.erode(img_thresh, kernel_1, iterations=1)
    img_dilation = cv.dilate(img_erosion, kernel_2, iterations=1)

    img_contours, img_hierarchy = cv.findContours(img_dilation, 2, 1)

    img_contours_list = []

    for img_contour in img_contours:
        # if cv.contourArea(img_contour) > 500:
        img_contours_list.append(img_contours)
    # 获取最大
    img_contour_area = max(img_contours_list)
    i = img_contours_list.index(img_contour_area)

    ret1 = cv.matchShapes(hua_contours[0], img_contours[i], 1, 0)
    ret2 = cv.matchShapes(fang_contours[0], img_contours[i], 1, 0)
    ret3 = cv.matchShapes(circle_contours[0], img_contours[i], 1, 0)

    if ret > 0.03:
        # 无匹配
        plate_type = "无"

    else:
        if ret1 == ret:
            # 匹配花盘子
            plate_type = "花盘子"
        elif ret2 == ret:
            # 匹配方盘子
            plate_type = "方盘子"
        else:
            plate_type = "圆盘子"

    return plate_type, ret


if __name__ == '__main__':
    plate_type, ret = matchTemp("./pic/fangcai.png")
    print(plate_type, ret)
